package com.tonyodev.fetchmigrator;

import ohos.app.Context;
import ohos.data.resultset.ResultSet;

import com.tonyodev.fetch2.database.DownloadDatabase;
import com.tonyodev.fetch2.database.DownloadInfo;
import com.tonyodev.fetch2.database.FetchDatabaseManagerImpl;
import com.tonyodev.fetch2.database.FetchDatabaseManagerWrapper;
import com.tonyodev.fetch2.fetch.LiveSettings;
import com.tonyodev.fetch2core.DefaultStorageResolver;
import com.tonyodev.fetch2core.FetchCoreUtils;
import com.tonyodev.fetch2core.FetchLogger;
import com.tonyodev.fetchmigrator.fetch1.DatabaseHelper;
import com.tonyodev.fetchmigrator.fetch1.DownloadTransferPair;
import com.tonyodev.fetchmigrator.helpers.TypeConverters;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据迁移实现类
 *
 * @since 2021-05-20
 */
public class FetchMigrator {
    /**
     * 迁移数据，从V1版本更新到V2版本
     *
     * @param context 上下文
     * @param v2Namespace V2版本命名
     * @param managerWrapper 数据库管理器包装类
     * @return 迁移后的数据集合
     */
    public static final List<DownloadTransferPair> migrateFromV1toV2(Context context,
                                                                     String v2Namespace,
                                                                     FetchDatabaseManagerWrapper managerWrapper) {
        DatabaseHelper fetchOneDatabaseHelper = new DatabaseHelper(context);
        fetchOneDatabaseHelper.clean();
        fetchOneDatabaseHelper.verifyOK();
        ArrayList downloadInfoList = new ArrayList<DownloadTransferPair>();
        LiveSettings liveSettings = new LiveSettings(v2Namespace);
        ResultSet cursor = fetchOneDatabaseHelper.get();
        if (cursor != null) {
            cursor.goToFirstRow();
            while (!cursor.isEnded()) {
                DownloadTransferPair downloadTransferPair = TypeConverters.v1CursorToV2DownloadInfo(cursor,
                    managerWrapper);
                DownloadInfo info = (DownloadInfo) downloadTransferPair.getNewDownload();
                info.setNamespace(v2Namespace);
                downloadInfoList.add(downloadTransferPair);
                cursor.goToNextRow();
            }
            cursor.close();
            FetchDatabaseManagerImpl fetchTwoDatabaseManager = new FetchDatabaseManagerImpl(
                context, v2Namespace, new FetchLogger(), DownloadDatabase.getMigrations(),
                liveSettings, false, new DefaultStorageResolver(context, FetchCoreUtils.getFileTempDir(context)));
            fetchTwoDatabaseManager.insert(new ArrayList<>(downloadInfoList));
            fetchTwoDatabaseManager.close();
        }
        fetchOneDatabaseHelper.close();
        return downloadInfoList;
    }

    /**
     * 删除V1版本数据库
     *
     * @param context 上下文
     */
    public static final void deleteFetchV1Database(Context context) {
        DatabaseHelper helper = new DatabaseHelper(context);
        helper.deleteRdbStore(DatabaseHelper.DB_NAME);
    }
}
